/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
*/

#include "OgreHardwarePixelBuffer.h"
#include "Texture.hpp"

namespace XernOgre
{
	Texture::Texture(Ogre::TexturePtr texture, TextureFormat format, size_t dataLen, const void *data)
		: texture(texture), format(format)
	{
		id = nil_uuid();
		pixelDataLen = dataLen;
		if(data)
		{
			pixelData = new char[pixelDataLen];
			memcpy(pixelData, data, pixelDataLen);
		}
		else
			pixelData = NULL;
	}

	Texture::~Texture()
	{
		delete pixelData;
	}

	IResource::ResourceFlags Texture::GetFlags() const
	{
		return RFL_CASHEABLE;
	}

	void Texture::UpdateState(boost::shared_ptr<IDataFilter> stateData)
	{
	}

	const uuid &Texture::GetId() const
	{
		return this->id;
	}

	void Texture::SetId(const uuid &id)
	{
		this->id = id;
	}

	int Texture::GetMipMaps() const
	{
		return texture->getNumMipmaps();
	}

	int Texture::GetWidth() const
	{
		return texture->getWidth();
	}

	int Texture::GetHeight() const
	{
		return texture->getHeight();
	}

	int Texture::GetDepth() const
	{
		return texture->getDepth();
	}

	ITexture::TextureFormat Texture::GetFormat() const
	{
		return format;
	}

	bool Texture::UploadLevel(int level, size_t len, const void *data)
	{
		// Get the level buffer.
		Ogre::HardwarePixelBufferSharedPtr buffer = texture->getBuffer(0, level);
		if(buffer.isNull())
			return false;

		// Lock the buffer.
		buffer->lock(Ogre::HardwareBuffer::HBL_NORMAL);

		// Send the data.
		const Ogre::PixelBox &pixelBox = buffer->getCurrentLock();
		memcpy(pixelBox.data, data, len);

		// Unlock the buffer.
		buffer->unlock();

		return true;
	}

	bool Texture::ReadLevel(int level, size_t len, void *buffer)
	{
		if(pixelData && pixelDataLen == len)
		{
			memcpy(buffer, pixelData, pixelDataLen);
			return true;
		}
		return false;
	}

}; // namespace XernOgre
